package com.toivan.mt.adapter;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hwangjr.rxbus.RxBus;
import com.toivan.mt.R;
import com.toivan.mt.model.MtSharedPrefKey;
import com.toivan.mt.model.MtToneFilterEnum;
import com.toivan.mt.model.RxBusAction;

import java.util.List;

public class MtToneFilterAdapter extends RecyclerView.Adapter<MtDesViewHolder> {

    private final List<MtToneFilterEnum> list;

    private int selectedPosition = MtSharedPrefKey.selectedPositionToneFilter;

    public MtToneFilterAdapter(List<MtToneFilterEnum> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public MtDesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mt_filter, parent, false);
        return new MtDesViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final MtDesViewHolder holder, int position) {
        if (position == 0) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) holder.itemView.getLayoutParams();
            p.setMargins((int) (holder.itemView.getContext().getResources().getDisplayMetrics().density * 24 + 0.5f), 0, 0, 0);
            holder.itemView.requestLayout();
        } else {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) holder.itemView.getLayoutParams();
            p.setMargins(0, 0, 0, 0);
            holder.itemView.requestLayout();
        }
        holder.textTV.setText(list.get(position).getString(holder.itemView.getContext()));
        holder.imageIV.setImageDrawable(list.get(position).getImageDrawable(holder.itemView.getContext()));

        if (selectedPosition == position) {
            holder.textTV.setSelected(true);
            holder.imageIV.setSelected(true);
            holder.coverIV.setVisibility(View.VISIBLE);
        } else {
            holder.textTV.setSelected(false);
            holder.imageIV.setSelected(false);
            holder.coverIV.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int lastPosition = selectedPosition;
                selectedPosition = holder.getAdapterPosition();
                MtSharedPrefKey.selectedPositionToneFilter = holder.getAdapterPosition();
                RxBus.get().post(RxBusAction.ACTION_TONE_FILTER, list.get(holder.getAdapterPosition()));
                notifyItemChanged(lastPosition);
                notifyItemChanged(selectedPosition);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }



}
